package com.tang;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 生产者：重试机制
 */
public class RetryProducer {
    public static void main(String[] args) throws Exception {
        //第二个参数开启消息追踪
        DefaultMQProducer producer = new DefaultMQProducer("producer_group", true);
        producer.setNamesrvAddr("127.0.0.1:9876");
        producer.start();
        List<Order> list1 = buildOrderList(1, 4, "Buy", "TG1");
        List<Order> list2 = buildOrderList(5, 4, "Buy", "TG2");
        List<Order> list3 = buildOrderList(9, 4, "Finish", "TG3");
        List<Order> orderList = new ArrayList<>();
        orderList.addAll(list1);
        orderList.addAll(list2);
        orderList.addAll(list3);
        int size = orderList.size();
        for (int i = 0; i < size; i++) {
            Order order = orderList.get(i);
            String info = order.toString();
            //这里的主题是局部有序的主题
            Message msg = new Message("Filter-Test-Topic", order.tag, info.getBytes());
            //setKeys这个方法就是设置每个消息的MessageKey
            msg.setKeys("Filter_Tag");
            //配合sql92实现消息过滤的写法
            msg.putUserProperty("idx",new DecimalFormat("00").format(order.orderId));
            producer.send(msg);
        }
        System.out.println("发送成功");
    }

    public static List<Order> buildOrderList(int orderId, int size, String desc, String tag) {
        List<Order> resultList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            int newOrderId = orderId + i;
            Order order = new Order();
            order.orderId = newOrderId;
            order.desc = desc;
            order.tag = tag;
            resultList.add(order);
        }
        return resultList;
    }

    public static class Order {
        /**
         * 订单id
         */
        int orderId;
        /**
         * 订单描述
         */
        String desc;

        String tag;

        @Override
        public String toString() {
            return "Order{" +
                    "orderId=" + orderId +
                    ", desc='" + desc + '\'' +
                    ", tag='" + tag + '\'' +
                    '}';
        }
    }
}